import loadding from "@/common/loading.js"
import user from "@/common/user.js"

let host = "";
//#ifndef H5
host = "http://121.40.202.15:40001" //"http://122.51.150.74:40001" //"https://pos.iyouhaolife.com"
//#endif
const timeout = 90000;


function objectToQueryString(obj) {

	return Object.keys(obj).map(function(key) {

		return "".concat(encodeURIComponent(key), "=").concat(encodeURIComponent(obj[key]));

	}).join('&');

}

function _request(options) {



	let requestConf = {
		method: options.method ? options.method : 'POST',
		url: host + options.url,
		timeout: timeout,
		success(ret) {
			//console.log(ret);
			if (!options.closeLoading) {
				loadding.hide();
			}
			if (ret.statusCode != 200 && user.getUserId()) {
				uni.showModal({
					title: '请求失败',
					content: '请联系管理员',
					showCancel: false,
				})
			} else {
				if (ret.data.success) {
					options.success(ret.data.data);
				} else {
					options.fail && options.fail(ret.data);
				}
			}
		},
		fail(err) {
			if (!options.closeLoading) {
				loadding.hide();
			}
			console.log(err);
			if (user.getUserId()) {
				uni.showModal({
					title: '网络请求失败',
					content: '请检查是否允许网络，或尝试重新打开 App',
					showCancel: false,
				})
			}

			options.fail && options.fail(err);
		},
		complete() {
			
		}
	}


	if (!options.data) {
		options.data = {};
	}

	if (options.params) {
		requestConf['url'] += '?' + objectToQueryString(options.params);
	}

	requestConf['data'] = options.data

	if (!options.type) {
		options.type = 'json';
	}
	if (options.type == 'json') {
		requestConf['dataType'] = 'json';
	}

	// header 头配置
	requestConf['header'] = {
		'Content-Type': options.type != 'json' ? 'application/x-www-form-urlencoded' : 'application/json',
	}


	if (!options.closeLoading) {
		loadding.show();
	}
	uni.request(requestConf);

}




const uploadFile = function(url,call,closeToast) {
	uni.chooseImage({
		success: (chooseImageRes) => {
			uni.showLoading({
				title: '文件上传中...'
			})
			const tempFilePaths = chooseImageRes.tempFilePaths;
			uni.uploadFile({
				url: host + url,
				filePath: tempFilePaths[0],
				name: 'file',
				success: (uploadFileRes) => {
					uni.hideLoading();
					try {
						if(!uploadFileRes) throw Error('kong')
						
						let data = JSON.parse(uploadFileRes.data)
						if(!data.data) throw Error('kong2')
						call(data.data);
						
						if(!closeToast){
							uni.showToast({
								icon: "success",
								title: '上传成功'
							})
						}
						
					} catch (e) {
						// uni.showModal({
						// 	showCancel: false,
						// 	title: '识别失败，请手动填写'
						// })
					}

				},
				fail: () => {
					uni.hideLoading();
					uni.showModal({
						showCancel: false,
						title: '上传失败'
					})
				},
				complete() {
					
				}
			});
		}
	});
}


export default {
	host: host,
	uploadFile: uploadFile,
	request: _request,
}
